﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletComponent : MonoBehaviour {

    private Rigidbody2D r;

    private ParticleSystem particles;

    private GameController gameController;

    private bool exploded = false;

    // Use this for initialization
    void Start () {
        r = GetComponent<Rigidbody2D>();
        particles = transform.Find("Particles").GetComponent<ParticleSystem>();
        if (GameObject.Find("Game"))
        {
            gameController = GameObject.Find("Game").GetComponent<GameController>();
        }
    }
	
	// Update is called once per frame
	void Update ()
    {

    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.layer != 10) // Undestructible
        {
            if (!exploded)
            {
                exploded = true;
                Destroy(collision.gameObject);
                Destroy(r);
                Destroy(transform.Find("Sprite").gameObject);
                /*particles.transform.SetParent(collision.gameObject.transform);
                particles.transform.localPosition = Vector3.zero;*/
                SpriteRenderer collisionSprite = collision.gameObject.GetComponent<SpriteRenderer>();
                if (collisionSprite != null)
                {
                    // XXX Not working
                    ParticleSystem.MainModule settings = particles.main;
                    settings.startColor = new ParticleSystem.MinMaxGradient(collisionSprite.color);
                }
                particles.Play();
                StartCoroutine(DestroyInOneSecond());

                if (collision.gameObject.GetComponent<SoldierController>() != null
                    || collision.gameObject.GetComponent<PlaneController>() != null
                    || collision.gameObject.GetComponent<GoalComponent>() != null)
                {
                    if (gameController)
                    {
                        gameController.Defeat();
                    }
                }
            }
        } else
        {
            Destroy(gameObject);
        }
    }

    IEnumerator DestroyInOneSecond()
    {
        yield return new WaitForSeconds(1);
        Destroy(gameObject);
    }
}
